package cn.com.pansky.comm.interceptor;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import net.vsame.url2sql.helper.Url2SqlContext;
import net.vsame.url2sql.helper.WebHelper;
import net.vsame.url2sql.sql.Model;
import net.vsame.url2sql.url.Interceptor;
import net.vsame.url2sql.url.impl.UrlMapping;
import net.vsame.url2sql.url.impl.UrlMapping.Chain;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UrlInterceptor implements Interceptor {

	
	@Override
	public void init(UrlMapping urlMapping, ServletContext servletContext) {
		
	}

	@SuppressWarnings("unchecked")
	@Override
	public void invoke(Chain chain) {
		Url2SqlContext c = WebHelper.getContext();
		HttpServletRequest request = WebHelper.getContext().getRequest();
		String encode = request.getCharacterEncoding();
		Map<String, String[]> map = c.getParams();
		Map<String, String[]> params = request.getParameterMap();
		ServletFileUpload upload = new ServletFileUpload();
		if (!params.isEmpty()) {
			for (String key : params.keySet()) {
				map.put(key, params.get(key));
			}
		}
		if (ServletFileUpload.isMultipartContent((HttpServletRequest) request)) {
			// file upload
			FileItemIterator iter = null;
			FileOutputStream fos;
			try {
				Properties p = new Properties();
				p.load(getClass().getClassLoader().getResourceAsStream("config.properties"));
				iter = upload.getItemIterator((HttpServletRequest) request);
				while (iter.hasNext()) {
					FileItemStream item = iter.next();
					if (!item.isFormField()) {
						InputStream in = item.openStream();
						byte[] fileData = readInputStream(
								Charset.forName(encode), in);
						
						String userId = "";
						if ("/unit/user/reg".equals(c.getRequestUrl()) || "/zgss/auth".equals(c.getRequestUrl()) || "/myAccount/register/saveUserInfo".equals(c.getRequestUrl())) {
							userId = UUID.randomUUID().toString();
						} else {
							Model m = (Model)request.getSession().getAttribute("user");
							userId = m.getString("AA001");
						}
						
						File file = new File(p.getProperty("imgPath")+userId+"_"+item.getFieldName()+".JPG"); //
						
						
						fos = new FileOutputStream(file);
						fos.write(fileData);
						fos.flush();
						fos.close();
						map.put(item.getFieldName(),
								new String[] { file.getPath() });
					} else {
						String value = inputStream2String(item.openStream(), encode);
						map.put(item.getFieldName(), new String[] { value });
						System.out.println("接收参数："+item.getFieldName()+"="+value);
					}
				}
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
		chain.next();
	}

	@Override
	public void destroy() {
	}

	private static byte[] readInputStream(Charset charset, InputStream in)
			throws IOException {
		byte[] bytes = new byte[1024];
		int length = -1;
		ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
		while ((length = in.read(bytes)) != -1) {
			byteOutput.write(bytes, 0, length);
		}
		byte[] data = byteOutput.toByteArray();
		return data;
	}
	public static String inputStream2String(InputStream is, String encode) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int i = -1;
		while ((i = is.read()) != -1) {
			baos.write(i);
		}
		return baos.toString(encode);
	}
}
